﻿using Flurl.Http;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Input;
using TiaoTiaoCode.AutoUpdate.Common.Exceptions;
using TiaoTiaoCode.AutoUpdate.ServerUI.Biz;
using TiaoTiaoCode.AutoUpdate.ServerUI.Splashs;
using TiaoTiaoCode.Common.Extensions;
using TiaoTiaoCode.Common.Helpers;

namespace TiaoTiaoCode.AutoUpdate.ServerUI.ViewModels
{
    public class UploadPublishZipViewModel : BindableBase, IDialogAware
    {
        #region 字段

        const string UploadApi = "api/serverUI/upload";

        readonly TiaoTiaoIniFile _iniFile;

        readonly SplashManager _splash;

        #endregion

        #region 属性

        private string zipFile = default!;
        private string programName = default!;
        private bool isEnable = true;
        private List<string> appNames = default!;

        /// <summary>
        /// 主应用程序名
        /// </summary>
        public string ProgramName
        {
            get { return programName; }
            set { SetProperty(ref programName, value); }
        }

        /// <summary>
        /// Zip更新包
        /// </summary>
        public string ZipFile
        {
            get { return zipFile; }
            set { SetProperty(ref zipFile, value); }
        }

        /// <summary>
        /// 窗体是否可用
        /// </summary>
        public bool IsEnable
        {
            get { return isEnable; }
            set { SetProperty(ref isEnable, value); }
        }

        /// <summary>
        /// 应用列表
        /// </summary>
        public List<string> AppNames
        {
            get { return appNames; }
            set { SetProperty(ref appNames, value); }
        }

        #endregion

        #region 命令

        ICommand? uploadCommand;
        ICommand? appNamesDropdownOpenCommand;

        /// <summary>
        /// 更新包上传
        /// </summary>
        public ICommand UploadCommand => uploadCommand ?? (uploadCommand = new DelegateCommand(UploadUpgradeZip));

        /// <summary>
        /// 应用程序名下拉列表展开事件
        /// </summary>
        public ICommand AppNamesDropdownOpenCommand => appNamesDropdownOpenCommand ?? (appNamesDropdownOpenCommand = new DelegateCommand(AppNamesDropDownOpen));

        #endregion

        public UploadPublishZipViewModel(SplashManager screenSplashLoading)
        {
            _splash = screenSplashLoading;

            _iniFile = new TiaoTiaoIniFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "setting.ini"));
        }

        #region 命令实现

        /// <summary>
        /// 上传更新文件压缩包
        /// </summary>
        /// <exception cref="CustomException"></exception>
        async void UploadUpgradeZip()
        {
            if (ProgramName.TiaoTiaoIsNullOrEmpty()) throw new CustomException("程序名为空");
            if (ZipFile.TiaoTiaoIsNullOrEmpty()) throw new CustomException("压缩文件为空");
            if (!File.Exists(ZipFile)) throw new CustomException("升级包压缩文件不存在");

            var baseApi = _iniFile.Read("application", "baseApi", String.Empty);
            var url = $"{baseApi.TrimEnd('/')}/{UploadApi}";

            _splash.ShowLoading("正在上传...");
            IsEnable = false;

            await url.PostMultipartAsync(
                content =>
                {
                    content.AddString("programName", ProgramName);
                    content.AddFile("file", ZipFile, "multipart/form-data");
                });

            _splash.HideLoading();
            IsEnable = true;

            RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
        }

        /// <summary>
        /// 获取应用App下拉
        /// </summary>
        async void AppNamesDropDownOpen()
        {
            var lst = await AppListBiz.QueryAll();

            AppNames = lst.Select(t => t.ProgramName).Cast<string>().ToList();
        }

        #endregion

        #region IDialogAware 实现

        public string Title => "上传升级包";

        public event Action<IDialogResult>? RequestClose;

        public bool CanCloseDialog()
        {
            return IsEnable;
        }

        public void OnDialogClosed()
        {

        }

        public void OnDialogOpened(IDialogParameters parameters)
        {

        }


        #endregion
    }
}
